package org.demo.es.controller;

import org.demo.es.model.common.AjaxResult;
import org.demo.es.model.entity.Articles;
import org.demo.es.service.DocumentService;
import org.demo.es.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用于定义ElasticSearch的文章的增删改查操作
 * @author moxiaoli
 */
@RestController
@RequestMapping("/search")
public class SearchArtcleController {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private SearchService searchService;

    /**
     * 添加文章
     * @param article 文章
     * @return 是否添加成功
     */
    @GetMapping("/addArticle")
    public AjaxResult<Boolean> addArticle(Articles article){
        return AjaxResult.status(documentService.addDocument("blog", article.getId().toString(), article));
    }

    /**
     * 删除文章
     * @param id 文章id
     * @return 是否删除成功
     */
    @GetMapping("/deleteArticle")
    public AjaxResult<Boolean> deleteArticle(Integer id){
        return AjaxResult.status(documentService.deleteDocument("blog", id.toString()));
    }

    /**
     * 更新文章
     * @param article 文章
     * @return 是否更新成功
     */
    @GetMapping("/updateArticle")
    public AjaxResult<Boolean> updateArticle(Articles article){
        return AjaxResult.status(documentService.updateDocument("blog", article.getId().toString(), article, Articles.class));
    }

    /**
     * 获取文章
     * @param id 文章id
     * @return 文章数据
     */
    @GetMapping("/getArticle")
    public AjaxResult<Articles> getArticle(Integer id){
        return AjaxResult.data(documentService.getDocument("blog", id.toString(), Articles.class));
    }

    /**
     * 查询文章
     * @param query 查询语句
     * @return 查询结果
     */
    @GetMapping("/searchArticle")
    public AjaxResult<List<Articles>> searchArticle(String query){
        return AjaxResult.data("查询结果",searchService.searchDocument("blog", query, Articles.class));
    }

    /**
     * 查询文章
     * @param keyword 查询语句
     * @return 查询结果
     */
    @GetMapping("/searchArticleByKeyword")
    public AjaxResult<List<Articles>> searchArticleByKeyword(String keyword){
        return AjaxResult.data("查询结果",searchService.searchDocumentByKeyword("blog", keyword, Articles.class));
    }

}
